//
//  SYLJStatusCellPictureView.swift
//  Weibo10
//
//  Created by 刘俊 on 15/10/20.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SDWebImage

/// 配图视图格子间距
private let StatusCellPictureItemMargin: CGFloat = 8
/// 可重用标识符
let StatusPictureCellId = "StatusPictureCellId"

class SYLJStatusCellPictureView: UICollectionView {

    /// 微博视图模型
    var viewModel: StatusViewModel? {
        didSet {
            // 根据内容自动计算大小
            sizeToFit()
            reloadData()
        }
    }
    // sizeToFit()方法的内部实现
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }

    // MARK: - 构造函数
    init() {
        let layout = UICollectionViewFlowLayout()
        // item 布局
        layout.minimumInteritemSpacing = StatusCellPictureItemMargin
        layout.minimumLineSpacing = StatusCellPictureItemMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        backgroundColor = UIColor(white: 1, alpha: 1.0)
        
        // 设置数据源 - 自己当自己的数据源
        // 应用
        dataSource = self
        // 设置代理
        delegate = self
        
        registerClass(SYLJStatusCellPictureCell.self, forCellWithReuseIdentifier:StatusPictureCellId)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
// MARK: - UICollectionViewDataSource
extension SYLJStatusCellPictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureCellId, forIndexPath: indexPath) as! SYLJStatusCellPictureCell
        cell.imageURL = viewModel?.thumbnailUrls![indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("选中了图片")
        print(viewModel!.thumbnailUrls![indexPath.item])
        // 发送通知传递数据(图片地址数组和对应的索引值)
        NSNotificationCenter.defaultCenter().postNotificationName(WBStatusSelectedPhotoNotification, object: self, userInfo: [WBStatusSelectedPhotoURLKey: viewModel!.thumbnailUrls!,WBStatusSelectedPhotoIndexPathKey: indexPath])
    }
}
// MARK: - item
class SYLJStatusCellPictureCell: UICollectionViewCell {
 
    // MARK: -视图对象
    var imageURL: NSURL? {
        didSet {
           iconView.sd_setImageWithURL(imageURL, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed,SDWebImageOptions.RefreshCached])
        }
    }
    // MARK: -构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - 懒加载控件
    private lazy var iconView: UIImageView = {
        let icon = UIImageView()
        // 设置图片填充模式
        icon.contentMode = UIViewContentMode.ScaleAspectFill
        icon.clipsToBounds = true
        return icon
    }()
    // 设置UI
    private func setupUI() {
        // 添加控件
        contentView.addSubview(iconView)
        // 设置frame
//        iconView.frame = self.bounds
        // 这里需要设置自动布局
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
}
//MARK: - 计算视图大小
extension SYLJStatusCellPictureView {
    private func calcViewSize() -> CGSize {
        // 准备
        let collW = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin //collectionView 的最大的大小
        let rowCount: CGFloat = 3 //一行的item数量
        let itemW = CGFloat(Int((collW - (rowCount - 1) * StatusCellPictureItemMargin) / rowCount))  // item的宽度
        
        // 获得layout
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemW, height: itemW)
        
        // 获取图片的数量
        let imageCount = viewModel?.thumbnailUrls?.count ?? 0
        
        if imageCount == 0 {
            return CGSizeZero
        }
        if imageCount == 1 {
            var size = CGSize(width: 12, height: 15)
            // 获得缓存的图片
            // 利用 SDWebImage 检查本地的缓存图像 - key 就是 url 的完整字符串
            // 问：SDWebImage 是如何设置缓存图片的文件名 完整 URL 字符串 -> `MD5`
            if let key = viewModel?.thumbnailUrls?.last?.absoluteString { // 获得key
                let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
                size = CGSize(width: image.size.width, height: image.size.height)
            }
            size.width = size.width < 40 ? 40 : size.width
            if size.width > 300 {
                let w: CGFloat = 300
                let h = size.height * w / size.width
                size = CGSize(width: w, height: h)
            }
            layout.itemSize = size
            return size
        }
        if imageCount == 4 {
            let w = StatusCellPictureItemMargin + 2 * itemW
            return CGSize(width: w, height: w)
        }
//        let row = CGFloat((count - 1) / Int(rowCount) + 1)

        let itemRowCount = CGFloat((imageCount - 1) / Int(rowCount) + 1)  //item 的行数
        let w = collW
        let h = itemRowCount * itemW + (itemRowCount - 1) * StatusCellPictureItemMargin
        
        return CGSize(width: w, height: h)
    }
}
